package cn.xdf.demo01;

import cn.xdf.entity.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class Demo02_增删改查 {
    //创建实体类管理器工厂对象
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("dev");//持久化单元

    //创建实体管理器
    EntityManager entityManager=entityManagerFactory.createEntityManager();

    //获取事务管理器
    EntityTransaction transaction = entityManager.getTransaction();

    @Before
    public void begin(){
        //开启事务
        transaction.begin();

    }

    @After
    public void after(){
        //提交事务
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }


    @Test
    public void test01(){
        //增
        User user=new User(null,"xiaohui","2000-10-10","男","广州");
        entityManager.persist(user);
    }


    @Test
    public void test02(){
        //查
        User user = entityManager.find(User.class, 1);
        System.out.println(user);
    }


    @Test
    public void test03(){
        //改，查出来再set改
        User user = entityManager.find(User.class, 1);
        user.setAddress("东莞");
        entityManager.persist(user);
    }


    @Test
    public void test04(){
        //删,查一个实体类，再remove这个
        User user = entityManager.find(User.class, 1);
        entityManager.remove(user);
    }


}
